import Vue from 'vue'
import Router from 'vue-router'
import { hasIn } from 'lodash'
import menu from '@/config/menu/index'
import Layout from '@/pages/Layout'
import Login from './Login'

Vue.use(Router)
// 根据菜单的配置转成路由的配置
const menuToRoute = () => {
  let arr = []
  for (let item of menu) {
    let o = {}
    o.path = item.path
    o.name = item.name
    o.component = Layout
    o.children = []
    for (let cItem of item.children) {
      if (cItem.children.length > 0) {
        // 如果有三级菜单
        for (let gItem of cItem.children) {
          let childrenO = {}
          childrenO.path = hasIn(gItem, 'dynamic') ? gItem.dynamic : gItem.path
          childrenO.name = gItem.name
          childrenO.component = resolve => require(['../components/' + gItem.componentPath + '.vue'], resolve)
          o.children.push(childrenO)
        }
      } else {
        // 如果仅有二级菜单
        let childrenO = {}
        childrenO.path = hasIn(cItem, 'dynamic') ? cItem.dynamic : cItem.path
        childrenO.name = cItem.name
        if (hasIn(cItem, 'componentPath')) {
          childrenO.component = resolve => require(['../components/' + cItem.componentPath + '.vue'], resolve)
        }
        o.children.push(childrenO)
      }
    }
    o.children.push({
      path: item.path,
      redirect: item.defaultPath
    })
    o.children.push({
      path: item.path + '/*',
      redirect: item.defaultPath
    })
    arr.push(o)
  }
  return arr
}
let routers = menuToRoute()

routers.push(Login)
routers.push({
  path: '/',
  redirect: '/home/readme'
})
routers.push({
  path: '*',
  redirect: '/home/readme'
})

export default new Router({
  routes: routers
})
